package sso.interceptor;


import io.jsonwebtoken.Claims;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.web.servlet.HandlerInterceptor;
import sso.util.JwtUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class ResourceInterceptor implements HandlerInterceptor{
 @Override
 public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) throws Exception{
  String token=request.getHeader("token");
  if(token==null||"".equals(token))
   throw new RuntimeException("请先登录");
  if(JwtUtils.isTokenExpired(token))
   throw new RuntimeException("登录超时，请重新登录");
  Claims claims=JwtUtils.getClaimsFormToken(token);
  List<String> list=(List<String>)claims.get("authorities");
  UserDetails userDetails=User.builder()
      .username((String)claims.get("username"))
       .password("").authorities(list.toArray(new String[]{}))
       .build();
  PreAuthenticatedAuthenticationToken authToken=
     new PreAuthenticatedAuthenticationToken(
      userDetails,userDetails.getPassword(),
      userDetails.getAuthorities()
     );
  authToken.setDetails(new WebAuthenticationDetails(request));
  SecurityContextHolder.getContext().setAuthentication(authToken);

  return true;
 }
}
